use std::{thread, time};
use colored::Colorize;
// src/commands/system_ops/top.rs
use sysinfo::{Process, System};

pub fn execute(args: &[String]) {
    let mut system = System::new_all();
    let mut refresh_interval = time::Duration::from_secs(3); // 默认刷新间隔
    let mut display_count = usize::MAX; // 默认显示所有进程
    let mut specific_pid: Option<u32> = None;

    // 解析命令行参数
    let mut i = 1;
    while i < args.len() {
        match args[i].as_str() {
            "-n" => {
                i += 1;
                if i < args.len() {
                    display_count = args[i].parse().unwrap_or(usize::MAX);
                }
            }
            "-s" => {
                i += 1;
                if i < args.len() {
                    if let Ok(seconds) = args[i].parse::<u64>() {
                        refresh_interval = time::Duration::from_secs(seconds);
                    }
                }
            }
            "-p" => {
                i += 1;
                if i < args.len() {
                    specific_pid = args[i].parse().ok();
                }
            }
            _ => {}
        }
        i += 1;
    }

    // 主循环
    loop {
        // 更新系统信息
        system.refresh_all();

        // 获取当前所有进程的信息
        let mut processes: Vec<&Process> = system.processes().iter().map(|(_, p)| p).collect();

        // 过滤特定 PID
        if let Some(pid) = specific_pid {
            //processes.retain(|&p| p.pid() == pid);
            processes.retain(|&p| p.pid().as_u32() == pid);
        }

        // 按照 CPU 使用率进行排序
        processes.sort_by(|a, b| b.cpu_usage().partial_cmp(&a.cpu_usage()).unwrap_or(std::cmp::Ordering::Equal));

        // 打印表头
        println!("{:<5}\t{:<25}\t{:<8}\t{:<10}\t{:<10}",
                 "PID", "Name", "CPU(%)", "Mem(KB)", "State");
        println!("{}", "-".repeat(80));

        // 取 processes 前10条记录
        processes.truncate(15);

        // 打印进程信息
        for process in processes.iter().take(display_count) {
            let pid = process.pid();
            let name = process.name().to_str().unwrap_or("N/A");
            let cpu_usage = process.cpu_usage();
            let memory = process.memory();
            let status = if process.status().eq(&sysinfo::ProcessStatus::Run) {
                "运行中"
            } else {
                "已停止"
            };

            println!("{:<5}\t{:<25}\t{:<8}\t{:<10}\t{:<10}",
                     pid, name.blue(), cpu_usage, (memory / 1024) as u32, status);
        }

        // 等待一段时间后刷新
        thread::sleep(refresh_interval);
    }
}
